﻿using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Diagnostics; 
using System.ComponentModel;
using System.Collections.Specialized;
using System.Configuration.Install;
using System.Windows.Forms; 
using Microsoft.Win32;

namespace MyInstaller
{
	[RunInstaller(true)]
	public class Installer : System.Configuration.Install.Installer
	{
		public bool	  Done=false;
		public string _DB;
		public string _User;
		public string _Pass;

		public Alert  Thongbao=null;
		public string SearchFile(string DirPath, string FileName)
		{
			string result="";
			DirectoryInfo di = new DirectoryInfo(DirPath);
			FileInfo[] fiArr = di.GetFiles();
			foreach (FileInfo fri in fiArr)
			{
				if(fri.Name.ToUpper().Equals(FileName.ToUpper()))
				{
          result=fri.FullName; 
					break;
				}
			}
			if(result.Equals(""))
			{
				DirectoryInfo[] diArr = di.GetDirectories();
				foreach (DirectoryInfo dri in diArr)
				{
					this.tmrProcess();
					result=SearchFile(dri.FullName,FileName);
					if(!result.Equals("")) break;
				}
			}
			return result;
		}
		
		public Installer():base()
		{
			InitializeComponent();
		}

		public void ShowContext()
		{
			//Dùng kiểm tra các thông số xử lý
			try
			{
				Info ifo=new Info();
				ifo.txtInfo.Text+="---base.Context.Parameters---\r\n";
				if ( base.Context.Parameters.Count > 0 )
				{
					foreach( string myString in base.Context.Parameters.Keys)
					{
						ifo.txtInfo.Text+=base.Context.Parameters[ myString ]+"\r\n" ;
					}
				}
				ifo.txtInfo.Text+="---base.Parent.Context.Parameters---\r\n";
				if ( base.Parent.Context.Parameters.Count > 0 )
				{
					foreach( string myString in base.Parent.Context.Parameters.Keys)
					{
						ifo.txtInfo.Text+=base.Parent.Context.Parameters[ myString ]+"\r\n" ;
					}
				}
				ifo.ShowDialog(); 
			}
			catch(Exception ex)
			{
				throw new Exception(ex.Message); 
			}
		}

		public override void Install(IDictionary savedState)
		{
			base.Install(savedState);
			this.Done = false;
			this.Thongbao.Text = "Searching SQL Server...";
			this.Thongbao.RollBack = false;
			this.Thongbao.Show();			

			string SQLinfo = Context.Parameters["SQLinfo"].ToString();
			string[] arrSQLinfo = SQLinfo.Split('/');

			this._DB	= arrSQLinfo[0];
			this._User	= arrSQLinfo[1];
			this._Pass	= arrSQLinfo[2];

			RegistryKey key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\80\Tools\ClientSetup");
			if (key1 == null)
			{
				key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer\Setup");
			}
			string strPathOsql = key1.GetValue("SQLPath").ToString() + @"\Binn\osql.exe";
			if (key1 != null)
			{
				string ScriptPath="";
				if ( Context.Parameters.Count > 0 )
				{
					ScriptPath	=	Context.Parameters["assemblypath"];
				}
				FileInfo fi	=	new FileInfo(ScriptPath);
				ScriptPath	=	fi.DirectoryName; 

				if (fi.Exists)
				{
					this.Thongbao.Text = "Attaching database...";
					string strConn = "Provider=SQLOLEDB.1;Server=" + this._DB + ";Initial Catalog=Master;User ID=" + this._User + ";Password=" + this._Pass + ";";
					string strAttach = "sp_attach_db @dbname = N'TTH_INTRANET_FR',@filename1 = N'" + ScriptPath + @"\Database\TTH_INTRANET_FR_Data.MDF',@filename2 = N'" + ScriptPath + @"\Database\TTH_INTRANET_FR_Log.LDF'";
					OleDbConnection conn = new OleDbConnection(strConn);
					conn.Open();
					OleDbTransaction dbTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
					OleDbCommand dbCommand = new OleDbCommand(strAttach, conn, dbTrans);
					dbCommand.ExecuteNonQuery();

					dbTrans.Commit();
					conn.Close();

					savedState.Add("OsqlEngine", strPathOsql);
					savedState.Add("WorkingFolder", ScriptPath);
					savedState.Add("DBExisted", "HueSoft");
					savedState.Add("DB", this._DB);
					savedState.Add("User", this._User);
					savedState.Add("Pass", this._Pass);
				}
			}
			else
			{
				MessageBox.Show("You must yourself setup the database later !", "Database setup");
			}
			for (int num1 = 0; num1 < 100; num1++)
			{
				this.tmrProcess();
			}
			this.Done = true;
			this.tmrProcess();
		}
 
/*
		public override void Install(IDictionary savedState)
		{
			base.Install(savedState);
			this.Done=false;
			this.Thongbao.Text="Searching SQL Server...";
			this.Thongbao.RollBack=false;
			this.Thongbao.Show();

			string ScriptPath="";
			if ( Context.Parameters.Count > 0 )
			{
				ScriptPath=Context.Parameters["assemblypath"];
			}
			FileInfo fi= new FileInfo(ScriptPath);
			ScriptPath=fi.DirectoryName; 

			RegistryKey key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\80\Tools\ClientSetup");
			if (key1 == null)
			{
				key1 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSSQLServer\Setup");
			}
			if (key1 != null)
			{				
				this.Thongbao.Text="Attach database...";

				string SQLinfo = Context.Parameters["SQLinfo"].ToString();
				string[] arrSQLinfo = SQLinfo.Split('/');
				string txtDB	=	arrSQLinfo[0].ToString();
				string txtUser	=	arrSQLinfo[1].ToString();
				string txtPass	=	arrSQLinfo[2].ToString();

				string strDataFiles = ScriptPath + @"\Database\TTH_INTRANET_FR_Data.mdf" +"," + ScriptPath + @"\Database\TTH_INTRANET_FR_Log.ldf"; 

				SQLDMO.SQLServer oSQL = new SQLDMO.SQLServer();
				oSQL.Connect(txtDB,txtUser,txtPass);
				oSQL.AttachDB("TTH_INTRANET_FR",strDataFiles);
					
				savedState.Add("DB",txtDB);
				savedState.Add("USER",txtUser);
				savedState.Add("PASS",txtPass);
				savedState.Add("WorkingFolder",ScriptPath); 
				savedState.Add("DBExisted","HueSoft"); 
			}
			else
			{
				MessageBox.Show("You must yourself setup the database later !","Database setup"); 
			}
			for(int i=0;i<100;i++) this.tmrProcess();
			this.Done=true;
			this.tmrProcess();
		}
		
		public override void Uninstall(IDictionary savedState)
		{  
			if(savedState.Equals(null)) return; 
			base.Uninstall(savedState);
			if(!savedState.Contains("DBExisted")) return;
			this.Done=false;
			this.Thongbao.Text="Uninstalling database...";
			this.Thongbao.RollBack=true;
			this.Thongbao.Show();			

			string txtDB	=	savedState["DB"].ToString();
			string txtUser	=	savedState["USER"].ToString();
			string txtPass	=	savedState["PASS"].ToString();

			SQLDMO.SQLServer oSQL = new SQLDMO.SQLServer();
			oSQL.Connect(txtDB,txtUser,txtPass);
			oSQL.DetachDB("TTH_INTRANET_FR",true);

			for(int i=0;i<100;i++) this.tmrProcess();
			this.Done=true;
			this.tmrProcess();
		}
		*/
		public override void Uninstall(IDictionary savedState)
		{
			if (!savedState.Equals(null))
			{
				base.Uninstall(savedState);
				if (savedState.Contains("DBExisted"))
				{
					this.Done = false;
					this.Thongbao.Text = "Uninstalling database...";
					this.Thongbao.RollBack = true;
					this.Thongbao.Show();

					this._DB	=	savedState["DB"].ToString();
					this._User	=	savedState["User"].ToString();
					this._Pass	=	savedState["Pass"].ToString();

					string strConn = "Provider=SQLOLEDB.1;Server=" + this._DB + ";Initial Catalog=Master;User ID=" + this._User + ";Password=" + this._Pass + ";";
					string strDetach = "sp_detach_db 'TTH_INTRANET_FR', 'true'";
					OleDbConnection conn = new OleDbConnection(strConn);
					conn.Open();
					OleDbTransaction dbTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted);					
					OleDbCommand dbCommand = new OleDbCommand(strDetach, conn,dbTrans);
					dbCommand.ExecuteNonQuery();
					dbTrans.Commit();
					conn.Close();

					for (int num1 = 0; num1 < 100; num1++)
					{
						this.tmrProcess();
					}
					this.Done = true;
					this.tmrProcess();
				}
			}
		}


		public override void Rollback(IDictionary savedState)
		{
			base.Rollback(savedState);
			if (savedState.Contains("DBExisted"))
			{
				this.Done = false;
				this.Thongbao.Text = "Rolling back database...";
				this.Thongbao.RollBack = true;
				this.Thongbao.Show();
				
				this._DB	=	savedState["DB"].ToString();
				this._User	=	savedState["User"].ToString();
				this._Pass	=	savedState["Pass"].ToString();

				string strConn = "Provider=SQLOLEDB.1;Server=" + this._DB + ";Initial Catalog=Master;User ID=" + this._User + ";Password=" + this._Pass + ";";
				string strDetach = "sp_detach_db 'TTH_INTRANET_FR', 'true'";
				OleDbConnection conn = new OleDbConnection(strConn);
				conn.Open();
				OleDbTransaction dbTrans = conn.BeginTransaction(IsolationLevel.ReadCommitted);					
				OleDbCommand dbCommand = new OleDbCommand(strDetach, conn,dbTrans);
				dbCommand.ExecuteNonQuery();
				dbTrans.Commit();
				conn.Close();

				for (int num1 = 0; num1 < 100; num1++)
				{
					this.tmrProcess();
				}
				this.Done = true;
				this.tmrProcess();
			}
		}


		public override void Commit(IDictionary savedState)
		{
			base.Commit(savedState);
		}

		private void InitializeComponent()
		{
			this.Thongbao = new MyInstaller.Alert();
		}

		private void tmrProcess()
		{
			if(this.Done) this.Thongbao.Hide();
			else
			{
				if(this.Thongbao.RollBack)
				{
					if(this.Thongbao.prgbShow.Value>0) this.Thongbao.prgbShow.Value-=1;
					else this.Thongbao.prgbShow.Value=100;
				}
				if(!this.Thongbao.RollBack)
				{
					if(this.Thongbao.prgbShow.Value<100) this.Thongbao.prgbShow.Value+=1;
					else this.Thongbao.prgbShow.Value=0;
				}
			}
		}
   	}
}
